package org.jiucheng.magpiebridge.server.aio.proxy.http11;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.text.MessageFormat;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jiucheng.magpiebridge.server.util.ServerCfg;
import org.jiucheng.magpiebridge.util.ThreadManager;

/**
 * 
 * @author jiucheng
 *
 */
public class Http11Proxy {
    private static final Logger LOGGER = Logger.getLogger(Http11Proxy.class.getName());
    
	public static void start() throws IOException {
		String serverMappings = ServerCfg.getServerMappings();
		if (serverMappings != null && !serverMappings.trim().isEmpty()) {
			String[] ipAndPort = serverMappings.split(":");
			
	        AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(ThreadManager.singleton());
	        final AsynchronousServerSocketChannel onlyProxy = AsynchronousServerSocketChannel.open(group);
	        onlyProxy.setOption(StandardSocketOptions.SO_REUSEADDR, true);
	        onlyProxy.setOption(StandardSocketOptions.SO_RCVBUF, 64 * 1024 * 1024);
	        
	        onlyProxy.bind(new InetSocketAddress(ipAndPort[0], Integer.valueOf(ipAndPort[1])));
            onlyProxy.accept(onlyProxy, new Http11ProxyEstablishmentCompletionHandler());
            
            if (LOGGER.isLoggable(Level.INFO)) {
                LOGGER.log(Level.INFO, MessageFormat.format("OnlyProxy started({0})", serverMappings));
            }
		}
	}
}
